import { ElMessage } from "element-plus";
import { putRestfulV2MallCouponStatus, putRestfulMallItemStatus, putRestfulMallConglomerationStatus } from "@/assets/api";

export const couponStatusApi = async (data: ObjValueAny, id: number): Promise<number> => {
    return await updateStatus(data, id, 'coupon');
}

export const itemStatusApi = async (data: ObjValueAny, id: number): Promise<number> => {
    return await updateStatus(data, id);
}

export const conglomerationStatusApi = async (data: ObjValueAny, id: number): Promise<number> => {
    return await updateStatus(data, id, 'groups');
}

const updateStatus = (data: ObjValueAny, id: number, type: string = 'item'): Promise<number> => {
    return new Promise(async resolve => {
        const statusesText: ObjValueStr = { 1: '上架', 4: '下架', 10: '审核', 7: '驳回' };
        ElMessage.closeAll();
        ElMessage({
            showClose: true,
            message: `${statusesText[data.status]}中...`,
            type: 'success',
            duration: 0,
        });
        let statusApi: Function = () => {
        };
        if (type === 'coupon') {
            statusApi = putRestfulV2MallCouponStatus
        }
        if (type === 'item') {
            statusApi = putRestfulMallItemStatus
        }
        if (type === 'groups') {
            statusApi = putRestfulMallConglomerationStatus
        }
        statusApi(id, data, { noRepeat: 3 }).then((resp: ObjValueAny) => {
            ElMessage.closeAll();
            if (resp.code === 200) {
                ElMessage.success(`${statusesText[data.status]}成功`);
                resolve(200);
            } else {
                ElMessage.error(resp.msg);
            }
            resolve(201);
        }).catch((error: ObjValueAny) => {
            ElMessage.closeAll();
            ElMessage.error(`操作失败：${error.status}`);
            resolve(201);
        })
    })
}